from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Department

User = get_user_model()

class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department
        fields = ['id', 'name', 'code', 'description', 'is_active']

class UserSerializer(serializers.ModelSerializer):
    department = DepartmentSerializer(read_only=True)
    department_id = serializers.PrimaryKeyRelatedField(
        queryset=Department.objects.all(),
        source='department',
        write_only=True,
        required=False
    )
    groups = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'email', 'first_name', 'last_name', 
                 'phone', 'department', 'department_id', 'title', 'is_active', 'groups']
        extra_kwargs = {
            'password': {'write_only': True},
            'is_active': {'read_only': True},
            'email': {'required': False},
            'phone': {'required': False},
            'first_name': {'required': False},
            'last_name': {'required': False},
            'title': {'required': False}
        }

    def get_groups(self, obj):
        return [group.name for group in obj.groups.all()]

    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise serializers.ValidationError("用户名已存在")
        return value

    def validate_email(self, value):
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError("邮箱已被注册")
        return value

    def validate_password(self, value):
        if len(value) < 6:
            raise serializers.ValidationError("密码长度不能小于6位")
        return value

    def create(self, validated_data):
        try:
            password = validated_data.pop('password', None)
            user = super().create(validated_data)
            if password:
                user.set_password(password)
                user.save()
            return user
        except Exception as e:
            raise serializers.ValidationError(f"创建用户失败: {str(e)}")

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True, error_messages={
        'required': '请输入用户名'
    })
    password = serializers.CharField(write_only=True, required=True, error_messages={
        'required': '请输入密码'
    }) 